/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.reddys.rad.inventory.controller;

import com.reddys.rad.inventory.db.Purchase;
import com.reddys.rad.inventory.db.PurchaseDetails;
import com.reddys.rad.inventory.db.PurchaseReturn;
import com.reddys.rad.inventory.db.PurchaseReturnDetails;
import com.reddys.rad.inventory.db.Stock;
import com.reddys.rad.inventory.db.StockDetails;
import com.reddys.rad.inventory.db.Vendor;
import com.reddys.rad.inventory.service.PurchaseOrderService;
import com.reddys.rad.inventory.service.PurchaseReturnService;
import com.reddys.rad.inventory.utils.EntityManagerImpl;
import com.reddys.rad.inventory.utils.Utilities;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.beans.property.Property;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.util.Callback;

/**
 * FXML Controller class
 *
 * @author REDDYS
 */
public class PurchaseReturnController implements Initializable {

    private  ObservableList productList =  FXCollections.observableArrayList();
      private  ObservableList data =  FXCollections.observableArrayList();
       private  ObservableList vendorList =  FXCollections.observableArrayList();
    @FXML
    TableView tableView;
    
    @FXML
    ComboBox vendiorID;
    
    @FXML
    ComboBox purchaseID;
    
    @FXML
    TextField purchaseReturnDescription;
    
    @FXML
    TextField purchaseDate;
    
    @FXML
    TextField remarks;
        
    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
         productList = new PurchaseReturnService().getPuschaseList();
         purchaseID.getItems().addAll(productList);
         vendorList = new PurchaseOrderService().getVendorList();
         vendiorID.getItems().addAll(vendorList);
         tableView.setEditable(true);
    
    
           purchaseID.focusedProperty().addListener(new ChangeListener<Boolean>() {
            @Override
            public void changed(ObservableValue observable, Boolean oldValue, Boolean newValue) {
                if (purchaseID.getSelectionModel()!=null) {
                   Purchase purchase = (Purchase) purchaseID.getSelectionModel().getSelectedItem();
                   data =  FXCollections.observableArrayList();
                   if(purchase!=null &&!Utilities.isNull(purchase.getPurchaseId())){
                       System.out.println(purchase.getPurchaseId());
                       ObservableList<PurchaseDetails> list= FXCollections.observableArrayList();
                       list = getPurchaseReturnService().getPurchaseDetailsList(purchase.getPurchaseId());
                        for(PurchaseDetails purchaseDetails:list){
                            ObservableList list1= FXCollections.observableArrayList();
                           list1.add(purchaseDetails.getProductCategoryDescription());
                           list1.add(purchaseDetails.getProductId());
                           list1.add(purchaseDetails.getProductId());
                          list1.add("");
                          list1.add("");
                          list1.add(purchaseDetails.getQuantity().toString());
                           list1.add(purchaseDetails.getUom());
                           list1.add("");
                          list1.add("");
                          list1.add("");
                          list1.add("");
                           data.add(list1);
                         } 
                       tableView.getItems().clear();
                        tableView.setItems(data);
                   }
                }
            }
        });
        purchaseID.setOnMouseReleased(new EventHandler() {
 
           @Override
           public void handle(Event t) {
                Purchase purchase = (Purchase) purchaseID.getSelectionModel().getSelectedItem();
                  data =  FXCollections.observableArrayList();
                   if(purchase!=null && !Utilities.isNull(purchase.getPurchaseId())){
                        System.out.println(purchase.getPurchaseId());
                   ObservableList list = getPurchaseReturnService().getPurchaseDetailsList(purchase.getPurchaseId());
                       for(int i=0;i<list.size();i++){
                          PurchaseDetails purchaseDetails = (PurchaseDetails) list.get(i);
                          ObservableList list1 = FXCollections.observableArrayList();
                          list1.add(purchaseDetails.getProductCategoryId());
                           list1.add(purchaseDetails.getProductId());
                           list1.add(purchaseDetails.getProductId());
                          list1.add("");
                          list1.add("");
                          list1.add(purchaseDetails.getQuantity().toString());
                           list1.add(purchaseDetails.getUom());
                           list1.add("");
                          list1.add("");
                          list1.add("");
                          list1.add("");
                          data.add(list1);
                       }
                   //    log.info("data--->"+data);
                       System.out.println(data);
                       tableView.getItems().clear();
                        tableView.setItems(data);
                   }
           }
        });
       loadTableColumns(tableView);
      // addEmptyRows();
    }    
    
        private void loadTableColumns(TableView tableView) {
   //     tableView.setEditable(true);
       TableColumn productCategory = new TableColumn("Product Category");
        productCategory.setMinWidth(100);
        Callback<TableColumn, TableCell> cellFactory =
             new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                    return new EditingCell();
                 }
             };
        
 /*       productCategory.setCellValueFactory(new Callback<CellDataFeatures<PurchaseOrderDetails, String>, String>() {

            @Override
            public String call(CellDataFeatures<PurchaseOrderDetails, String> p) {
               return p.getValue().getProductId().getProductId();
            }
  });*/
         productCategory.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
              return new SimpleStringProperty( 
                      cdf.getValue().get(0)!=null?cdf.getValue().get(0).toString():"");
            }
           

           
        });
/*        productCategory.setOnEditCommit(
                new EventHandler<TableColumn.CellEditEvent<PurchaseOrderDetails, String>>() {
                     
                    @Override 
                    public void handle(TableColumn.CellEditEvent<PurchaseOrderDetails, String> t) {
                         System.out.println(t);
                        System.out.println("before Setting"+((PurchaseOrderDetails)t.getTableView().getItems().get(t.getTablePosition().getRow())).getProductId());
                        ((PurchaseOrderDetails)t.getTableView().getItems().get(
                                t.getTablePosition().getRow())).setProductId(t.getNewValue());
                        System.out.println("after Setting"+((PurchaseOrderDetails)t.getTableView().getItems().get(t.getTablePosition().getRow())).getProductId());
                    }
                });
 */
        TableColumn productID = new TableColumn("Product ID");
        productID.setMinWidth(100);
       productID.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
              return new SimpleStringProperty( 
                      cdf.getValue().get(1).toString());
            }
              });
 /*       productID.setOnEditCommit(
            new EventHandler<CellEditEvent<PurchaseOrderDetails, String>>() {
                @Override
                public void handle(CellEditEvent<PurchaseOrderDetails, String> t) {
                    ((PurchaseOrderDetails) t.getTableView().getItems().get(
                        t.getTablePosition().getRow())
                        ).setProductId(t.getNewValue());
                }
             }
        );
 */
        TableColumn productName = new TableColumn("Product Name");
        productName.setMinWidth(200);
        productName.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
              return new SimpleStringProperty( 
                      cdf.getValue().get(2)!=null?cdf.getValue().get(2).toString():"");
            }  });
       // productName.setCellFactory(cellFactory);
        
        TableColumn itemCode = new TableColumn("Item Code");
        itemCode.setMinWidth(100);
        //itemCode.setCellFactory(cellFactory);
    itemCode.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
              return new SimpleStringProperty( 
                      cdf.getValue().get(3).toString());
            }  });
        TableColumn quantity = new TableColumn("Quantity");
        quantity.setMinWidth(100);
            quantity.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
              return new SimpleStringProperty( 
                      cdf.getValue().get(5)!=null?cdf.getValue().get(5).toString():"");
            }  });
        
        TableColumn uom = new TableColumn("Uom");
        uom.setMinWidth(100);
            uom.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
              return new SimpleStringProperty( 
                      cdf.getValue().get(6).toString());
            }  });
        TableColumn unitPrice = new TableColumn("Unit Price");
        unitPrice.setMinWidth(100);

            unitPrice.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
              return new SimpleStringProperty( 
                      cdf.getValue().get(7).toString());
            }  });
        TableColumn returned = new TableColumn("Returned");
        returned.setMinWidth(100);
        returned.setCellFactory( new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                    return new EditingCell("Returned");
                 }
         });
        TableColumn returnedremarks = new TableColumn("Remarks");
        returnedremarks.setMinWidth(100);

        returnedremarks.setCellFactory( new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                    return new EditingCell("remarks");
                 }
             });
        
        TableColumn subTotal = new TableColumn("Sub Total");
        subTotal.setMinWidth(100);
        tableView.getColumns().addAll(productCategory, productID, productName,itemCode, quantity, uom,unitPrice,subTotal,returned, returnedremarks);
        //tableView.getItems().addAll(data);
 
    }

    private void updatePurchase(String purchaseId, String productId,Double rejectedQuantity) {
        PurchaseDetails purchaseDetail = getPurchaseReturnService().getPurchaseDetailByPurchaseId(purchaseId,productId);
        purchaseDetail.setRejected(purchaseDetail.getRejected()!=null?purchaseDetail.getRejected():new Double("0.0")+rejectedQuantity);
        purchaseDetail.setQuantity(purchaseDetail.getQuantity()!=null?purchaseDetail.getQuantity():new Double("0.0") - rejectedQuantity);
    }

                 class EditingCell extends TableCell<Object, String> {
        private String columnName ;
        private TextField textField;

        public EditingCell() {
        }
       public EditingCell(String columnName ) {
           this.columnName = columnName;
        }
 
        @Override
        public void startEdit() {
           
                super.startEdit();
                createTextField();
                setText(null);
                setGraphic(textField);
                textField.selectAll();

        }
 
        @Override
        public void cancelEdit() {
            super.cancelEdit();
 
            setText((String) getItem());
            setGraphic(null);
        }
 
        @Override
        public void updateItem(String item, boolean empty) {
            super.updateItem(item, empty);
 
            if (empty) {
                setText(null);
                setGraphic(null);
            } else {
                if (isEditing()) {
                    if (textField != null) {
                        textField.setText(getString());
                    }
                    setText(null);
                    setGraphic(textField);
                } else {
                    setText(getString());
                    setGraphic(null);
                }
            }
        }
     public Property<String> inputText()
    {
        return textField.textProperty();
    }

        private void createTextField() {
            textField = new TextField(getString());
            textField.setMinWidth(this.getWidth() - this.getGraphicTextGap()* 2);
            textField.setOnKeyReleased(new EventHandler<KeyEvent>(){
               
                @Override
                public void handle(KeyEvent t) {
                       ObservableList tableData = (ObservableList) tableView.getSelectionModel().getSelectedItem();
                System.out.println("tableData"+tableData);
                    System.out.println("createtext"+textField.getText());
                    if(columnName.equalsIgnoreCase("Quantity")){

                        tableData.set(5, textField.getText());
                    }else if(columnName.equalsIgnoreCase("UOM")){
                        tableData.set(6, textField.getText());
                    }else if(columnName.equalsIgnoreCase("UnitPrice")){
                        tableData.set(8, textField.getText());
                    }else if(columnName.equalsIgnoreCase("Sub Total")){
                     tableData.set(7, textField.getText());
                    }
                    else if(columnName.equalsIgnoreCase("Returned")){
                      tableData.set(8, textField.getText());
                    }else if(columnName.equalsIgnoreCase("Remarks")){
                     tableData.set(9, textField.getText());
                    }
                }
                    
                
 
            });
            textField.setOnMouseExited(new EventHandler<MouseEvent>(){
         
                @Override
                public void handle(MouseEvent t) {
                      ObservableList tableData = (ObservableList) tableView.getSelectionModel().getSelectedItem();
                   System.out.println("createtext"+textField.getText());
                    if(columnName.equalsIgnoreCase("Quantity")){

                        tableData.set(5, textField.getText());
                    }else if(columnName.equalsIgnoreCase("UOM")){
                        tableData.set(6, textField.getText());
                    }else if(columnName.equalsIgnoreCase("UnitPrice")){
                        tableData.set(8, textField.getText());
                    }else if(columnName.equalsIgnoreCase("Sub Total")){
                     tableData.set(7, textField.getText());
                    }
                    else if(columnName.equalsIgnoreCase("Returned")){
                      tableData.set(8, textField.getText());
                    }else if(columnName.equalsIgnoreCase("Remarks")){
                     tableData.set(9, textField.getText());
                    }
                }
             });

         }
 
        private String getString() {
            return getItem() == null ? "" : getItem().toString();
        }
     }
     public PurchaseReturnService getPurchaseReturnService(){
        PurchaseReturnService purchaseReturnrvice = new PurchaseReturnService();
        return purchaseReturnrvice;
    }
     
             @FXML
        public PurchaseReturn save(){
             
            PurchaseReturn purchaseReturn = new PurchaseReturn();
            try{
            purchaseReturn.setPurchaseReturnDescription(purchaseReturnDescription.getText());
           //  purchase.setPurchaseDate(purchaseDescription.getText());
            Purchase purchase = (Purchase) purchaseID.getSelectionModel().getSelectedItem();
            purchaseReturn.setPurchaseId(purchase.getPurchaseId());
            Vendor vendor = (Vendor) vendiorID.getSelectionModel().getSelectedItem();
            purchaseReturn.setVendorId(vendor.getVendorid());
            purchaseReturn.setRemarks(remarks.getText());
            EntityManagerImpl.persist(purchaseReturn);
            ObservableList purchaseReturnDetailsList = tableView.getItems();
            for(int i=0;i<purchaseReturnDetailsList.size();i++){
                 ObservableList purchaseReturnDetailRowList = (ObservableList) purchaseReturnDetailsList.get(i);
                PurchaseReturnDetails purchaseDetails = new PurchaseReturnDetails();
               purchaseDetails.setPurchaseReturnId(purchaseReturn.getPurchaseReturnId());
                purchaseDetails.setProductId((String) purchaseReturnDetailRowList.get(1));
                purchaseDetails.setProductCategoryId((String) purchaseReturnDetailRowList.get(0));
               // purchaseDetails.setBatchCode((String) purchaseRowList.get(1));
                purchaseDetails.setQuantityReceived(Double.valueOf(Utilities.isNull(purchaseReturnDetailRowList.get(4).toString())?"0.0":purchaseReturnDetailRowList.get(4).toString()));
                purchaseDetails.setQuantityRejected(Double.valueOf(purchaseReturnDetailRowList.get(8).toString()));
                purchaseDetails.setUom((String) purchaseReturnDetailRowList.get(5));
                purchaseDetails.setRejectedRemarks((String) purchaseReturnDetailRowList.get(9));
                EntityManagerImpl.persist(purchaseDetails);
                updatePurchase(purchaseReturn.getPurchaseId(),purchaseDetails.getProductId(),purchaseDetails.getQuantityRejected());
              Stock stock = getPurchaseReturnService().getStock(purchaseDetails.getProductId());
              if(stock !=null){
              stock.setAvailableQuantity(stock.getAvailableQuantity()-purchaseDetails.getQuantityRejected());
                getPurchaseReturnService().updateStock(stock); 
              }

            }
                StockDetails stockDetails = new StockDetails();
                stockDetails.setStockDetailDescription(purchaseReturn.getPurchaseReturnDescription());
                stockDetails.setTransactionId(purchaseReturn.getPurchaseReturnId());
                stockDetails.setTransactionDate(Utilities.getCurrentDate());
                
             //   stockDetails.setQuantit(purchase.get);
                //stockDetails.setTransactionAmount(purchaseReturn.getTotalAmount());
                stockDetails.setTransactionType("purchase return");
                EntityManagerImpl.persist(stockDetails);
                Utilities.createDialog("Transaction completed successfully");
            }catch(Exception e){
                e.printStackTrace();
                //log.info(e.getMessage());
                Utilities.createDialog("Transaction Failed");
            }
            return purchaseReturn;
        }

}
